import torch  
import torch.nn as nn 

X = torch.tensor([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]).unsqueeze(1) # 定义输入数据X，改变结构为了之后前向传播使用
y = torch.tensor([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0]).unsqueeze(1)  # 定义真实标签y，改变结构为了之后前向传播使用
#定义多程感知机
class Perceptron(nn.Module):
    def __init__(self):
        super(Perceptron, self).__init__()
        self.fc1 = nn.Linear(1,2)
        self.fc2 = nn.Linear(2,1)       
    def forward(self, x):      
        y = torch.relu(self.fc1(x))
        y = self.fc2(y)  
        return y
model = Perceptron()
print("已经创建模型:", model) 
if model.training == True:
    print("模型当前(默认)处于训练模式")
loss_fnc = nn.MSELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
net_losses = []
for epoch in range(500):
    y_pred = model(X.unsqueeze(1))
    loss = loss_fnc(y_pred, y.unsqueeze(1))
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if (epoch+1) % 50 == 0:
        print(f'Epoch [{epoch+1}/500], Loss: {loss.item():.4f}')
model.eval()  # 将模型调整为评估模式
if not model.training:
    print("模型当前处于评估模式")
with torch.no_grad():
    x_test = torch.tensor([10.0])
    y_test = model(x_test.unsqueeze(0))
    print(f'测试输入x: {x_test.item()}')  
    print(f'测试输出y: {y_test.item()}')
